package nachos.threads;

import nachos.machine.*;

/**
 * A <i>communicator</i> allows threads to synchronously exchange 32-bit
 * messages. Multiple threads can be waiting to <i>speak</i>, and multiple
 * threads can be waiting to <i>listen</i>. But there should never be a time
 * when both a speaker and a listener are waiting, because the two threads can
 * be paired off at this point.
 */
public class Communicator {

	// The message
	private int message = 0;
	// The one lock
	private Lock lock = null;

	// flag to synchronize send/receive
	private boolean messageReady = false;
	
	// Conditions used to control thread states
	private Condition speakCondition = null;
	private Condition listenCondition = null;

	/**
	 * Allocate a new communicator.
	 */
	public Communicator() {
		lock = new Lock();
		speakCondition = new Condition(lock);
		listenCondition = new Condition(lock);
	}

	/**
	 * Wait for a thread to listen through this communicator, and then transfer
	 * <i>word</i> to the listener.
	 * 
	 * <p>
	 * Does not return until this thread is paired up with a listening thread.
	 * Exactly one listener should receive <i>word</i>.
	 * 
	 * @param word
	 *            the integer to transfer.
	 */
	public void speak(int word) {
		log("Communicator::speak() with <" + word + ">");
		lock.acquire();

		while(messageReady) {
			log("Communicator::speak - Send already in progress, sleeping...");
			speakCondition.sleep();
		}
		log("Communicator::speak - No senders waiting, continue...");

		// set message
		message = word;
		// reset flag
		messageReady = true;
		
		// wake waiting listener
		listenCondition.wakeAll();

		lock.release();
		log("Leaving Communicator::speak()");
	}

	/**
	 * Wait for a thread to speak through this communicator, and then return the
	 * <i>word</i> that thread passed to <tt>speak()</tt>.
	 * 
	 * @return the integer transferred.
	 */
	public int listen() {
		log("Entering listen(), listening...");
		lock.acquire();

		// if no message present, sleep
		while(!messageReady) {
			log("Communicator::listen - No message waiting, sleeping...");			
			listenCondition.sleep();
		}
		
		log("Communicator::listen - Message ready, waking up...");

		// reset flag
		messageReady = false;
		speakCondition.wakeAll();
		
		lock.release();
		log("Leaving listen() with <" + message + ">");		
		return message;
	}

	/*
	 * Test cases. Threw together two simple thread classes, one for speaking
	 * and the other for listening.
	 * 
	 */
	private static Communicator communicator = new Communicator();

	private static class CommunicatorSpeakerThread implements Runnable {
		int message;

		public CommunicatorSpeakerThread(int message) {
			this.message = message;
		}

		public void run() {
			communicator.speak(message);
		}
	}

	private static class CommunicatorListenerThread implements Runnable {
		public CommunicatorListenerThread() {
			// TODO Auto-generated constructor stub
		}

		public void run() {
			response = communicator.listen();
		}

		private int response;
	}
	
	private void log(String msg) {
		System.out.println("[" + KThread.currentThread().getName() + "]" + msg);
	}

	public static void selfTest() {
		System.out.println("Enter Communicator.selfTest");
		KThread speakerOne = new KThread(new CommunicatorSpeakerThread(100)).setName("speaker 1");
		KThread speakerTwo = new KThread(new CommunicatorSpeakerThread(200)).setName("speaker 2");
		//KThread speakerThree = new KThread(new CommunicatorSpeakerThread(300)).setName("speaker 2");
		KThread listenerOne = new KThread(new CommunicatorListenerThread()).setName("listener 1");
		KThread listenerTwo = new KThread(new CommunicatorListenerThread()).setName("listener 2");
		//KThread listenerThree = new KThread(new CommunicatorListenerThread()).setName("listener 3");

		listenerOne.fork();
		listenerTwo.fork();
		speakerOne.fork();
		speakerTwo.fork();
		//speakerThree.fork();
		//listenerThree.fork();

		listenerOne.join();
		listenerTwo.join();
		speakerOne.join();
		speakerTwo.join();
	}

}
